package com.gsww.vue.service.sys.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gsww.vue.dao.sys.SysMenuDao;
import com.gsww.vue.dao.sys.SysOperatorDao;
import com.gsww.vue.dao.sys.SysRoleAcctRelDao;
import com.gsww.vue.dao.sys.SysRoleDao;
import com.gsww.vue.dao.sys.SysRoleMenuRelDao;
import com.gsww.vue.dao.sys.SysRoleOperRelDao;
import com.gsww.vue.entity.sys.SysResourceTree;
import com.gsww.vue.entity.sys.SysRole;
import com.gsww.vue.entity.sys.SysRoleMenuRel;
import com.gsww.vue.entity.sys.SysRoleOperRel;
import com.gsww.vue.service.BasicService;
import com.gsww.vue.service.sys.SysRoleService;
import com.gsww.vue.utils.NullHelper;

import net.sf.json.JSONObject;

@Service
@Transactional
public class SysRoleServiceImpl extends BasicService implements SysRoleService {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private SysRoleAcctRelDao sysRoleAcctRelDao;
	@Autowired
	private SysRoleDao sysRoleDao;
	@Autowired
	private SysMenuDao sysMenuDao;
	@Autowired
	private SysOperatorDao sysOperatorDao;
	@Autowired
	private SysRoleOperRelDao sysRoleOperRelDao;
	@Autowired
	private SysRoleMenuRelDao sysRoleMenuRelDao;

	@Override
	public Map<String, Object> getRoleList(String roleName, String pageNo,String pageSize) throws Exception {
		List<Object> paramList = new ArrayList<Object>();
		Map<String,Object> resMap = new HashMap<String,Object>();
		StringBuilder sql = new StringBuilder("select * from sys_role t where 1=1 and t.role_state='1' ");
		if(StringUtils.isNotBlank(roleName)){
			sql.append(" and t.role_name like ? ");
			paramList.add("%"+roleName+"%");
		}
		sql.append(" order by t.create_time desc ");
		Map<String, Object> map = super.page(sql.toString(),paramList, pageNo, pageSize);
		return map;
	}

	@Override
	public String getAuthorizeTree(String roleId) throws Exception {
		//System.out.println("roleID="+roleId);
		// 1.获取资源及已授权记录
		StringBuffer resAndAccreditSql = new StringBuffer();
		resAndAccreditSql.append("select m.menu_id,m.menu_name,m.parent_menu_id,rm.role_menu_id from SYS_MENU m ");
		resAndAccreditSql.append(
				"left join sys_role_menu_rel rm on m.menu_id=rm.menu_id and rm.role_id=? where m.menu_state='1' ");
		resAndAccreditSql.append("order by m.menu_seq asc");
		//System.out.println(resAndAccreditSql);
		//System.out.println(roleId);
		List<Map<String, Object>> resAndAccreditList = jdbcTemplate.queryForList(resAndAccreditSql.toString(),
				roleId);
		// 2.获取操作及已授权记录
		StringBuffer operAndAccreditSql = new StringBuffer();
		operAndAccreditSql
				.append("select o.operator_id,o.menu_id,o.operator_name,ro.role_oper_id from sys_operator o ");
		operAndAccreditSql.append("left join sys_role_oper_rel ro on ro.operator_id=o.operator_id and ro.role_id=? ");
		operAndAccreditSql.append(
				"where o.operator_state='1' order by o.menu_id,o.tab_index,o.operator_type,o.operator_level asc");
		System.out.println(operAndAccreditSql);
		List<Map<String, Object>> operAndAccreditList = jdbcTemplate.queryForList(operAndAccreditSql.toString(),
				roleId);
		// 3.将资源及操作记录整合后放入List;
		List<SysResourceTree> list = new ArrayList<SysResourceTree>();
		for (Map<String, Object> map : resAndAccreditList) {
			SysResourceTree tree = new SysResourceTree();
			tree.setPkId(NullHelper.convertNullToNothingnull(map.get("MENU_ID")));
			tree.setName(NullHelper.convertNullToNothingnull(map.get("MENU_NAME")));
			tree.setTitle(tree.getName());
			tree.setParId(NullHelper.convertNullToNothingnull(map.get("PARENT_MENU_ID")));
			String roleResKey = NullHelper.convertNullToNothingnull(map.get("ROLE_MENU_ID"));
			//System.out.println("=="+roleResKey+""+"".equals(roleResKey));
			tree.setChecked("".equals(roleResKey) ? false : true);
			tree.setOpen(true);
//			tree.setHoriz(false);
//			tree.setCheckbox(true);
//			tree.setCustomType("res");
//			tree.setCheckInteractParent(true);
//			tree.setCheckInteractSub(true);
//			tree.setUncheckInteractParent(true);
//			tree.setUncheckInteractSub(true);
			list.add(tree);
		}
		for (Map<String, Object> map : operAndAccreditList) {
			SysResourceTree tree = new SysResourceTree();
			tree.setPkId("O_" + NullHelper.convertNullToNothingnull(map.get("OPERATOR_ID")));
			tree.setName(NullHelper.convertNullToNothingnull(map.get("OPERATOR_NAME")));
			tree.setTitle(tree.getName());
			//tree.setExpand(true);
			tree.setParId(NullHelper.convertNullToNothingnull(map.get("MENU_ID")));
			String roleOperKey = NullHelper.convertNullToNothingnull(map.get("ROLE_OPER_ID"));
			tree.setChecked("".equals(roleOperKey) ? false : true);
			tree.setOpen(true);
//			tree.setHoriz(true);
			//tree.setCheckbox(true);
//			tree.setCustomType("oper");
//			tree.setCheckInteractParent(true);
//			tree.setCheckInteractSub(true);
//			tree.setUncheckInteractParent(true);
//			tree.setUncheckInteractSub(true);
			list.add(tree);
		}

		// 4.创建树根
		SysResourceTree tree = new SysResourceTree();
		tree.setPkId("0");
		tree.setParId("-1");
		tree.setName("系统授权");
		tree.setTitle("系统授权");
		tree.setOpen(true);
		// 5.递归生产完整的树
		createTree(tree, list);
		// 6.生产JSON

		JSONObject jsonObject = JSONObject.fromObject(tree);
		String jsonStr = jsonObject.toString();
		jsonStr = jsonStr.replaceAll("\"nodes\":null", "\"nodes\":\\[\\]"); // "nodes":null替换为"nodes":[]
		//System.out.println("[" + jsonStr + "]");
		return "[" + jsonStr + "]";
	}

	// 递归创建资源授权树
	private void createTree(SysResourceTree parentNode, List<SysResourceTree> list) {
		List<SysResourceTree> clist = new ArrayList<SysResourceTree>();
		for (SysResourceTree tree : list) {
			if (parentNode.getPkId().equals(tree.getParId())) {
				SysResourceTree node = new SysResourceTree();
				node.setPkId(tree.getPkId());
				node.setParId(tree.getParId());
				node.setName(tree.getName());
				node.setTitle(tree.getName());
				node.setOpen(true);
//				if(tree.getPkId().contains("O")){
//					node.setChecked(tree.getChecked());
//				} 
				//System.out.println(tree.getName()+"--"+tree.getChecked());
				node.setChecked(tree.getChecked());
//				node.setChecked(tree.getChecked());
				//System.out.println(tree.getTitle()+"---"+tree.getChecked());

				clist.add(node);
				node = null;
			}
		}
		// 孩子获取下一级孩子
		if (clist.size() > 0) {
			//parentNode.setNodes(clist);
			parentNode.setChildren(clist);
			int selectNum = 0;
			for(SysResourceTree ctree : clist){
				if(ctree.getChecked()){//ctree.getPkId().contains("O") && 
					selectNum ++;
				}
			}
			//父级半选，子级一个都没选
			//System.out.println(parentNode.getName()+"--"+parentNode.getChecked());
			if(selectNum ==0 && parentNode.getChecked() != null && parentNode.getChecked()){
				parentNode.setChecked(false);
				parentNode.setSelected(true);
			}
			
			for (SysResourceTree ctree : clist) {
				createTree(ctree, list);// 递归
			}
		}
	}
	@Override
	public void saveAuthorize(String roleId,String keys) {
		String[] key = keys.split(",");
		//String[] type = types.split(",");
		// 删除该角色下的资源和操作授权
		List<SysRoleOperRel> list = sysRoleOperRelDao.findByRoleId(roleId);
		for(SysRoleOperRel rel : list){
			sysRoleOperRelDao.delete(rel);
		}
		List<SysRoleMenuRel> relList = sysRoleMenuRelDao.findByRoleId(roleId);
		for(SysRoleMenuRel rel : relList){
			sysRoleMenuRelDao.delete(rel);
		}
		//sysRoleOperRelDao.delete(sysRoleOperRelDao.findByRoleId(roleId));
		//sysRoleMenuRelDao.delete(sysRoleMenuRelDao.findByRoleId(roleId));
		// 新增该角色下的资源和操作授权
		SysRoleMenuRel sysRoleMenuRel;
		SysRoleOperRel sysRoleOper;
		for (int i = 0; i < key.length; i++) {
			//if ("res".equals(type[i])) {
			if (!key[i].contains("O")) {
				sysRoleMenuRel = new SysRoleMenuRel();
				sysRoleMenuRel.setRoleId(roleId);
				//sysRoleMenuRel.setSysMenu(sysMenuDao.findOne(key[i]));
				sysRoleMenuRel.setSysMenu(sysMenuDao.findByMenuId(key[i]));
				sysRoleMenuRelDao.save(sysRoleMenuRel);
			//} else if ("oper".equals(type[i])) { // 保存角色——操作数据
			} else if (key[i].contains("O")) { // 保存角色——操作数据
				sysRoleOper = new SysRoleOperRel();
				sysRoleOper.setRoleId(roleId);
				//sysRoleOper.setSysOperator(sysOperatorDao.findOne(key[i].substring(2, key[i].length())));
				sysRoleOper.setSysOperator(sysOperatorDao.findById(key[i].substring(2, key[i].length())).get());
				sysRoleOperRelDao.save(sysRoleOper);
			}
		}
	}

	@Override
	public List<SysRole> findRoleList() throws Exception {
		List<SysRole> list = new ArrayList<SysRole>();
		list = sysRoleDao.findAll();
		return list;
	}
	@Override
	public SysRole findByKey(String roleId) throws Exception {
		return sysRoleDao.findByRoleId(roleId);
	}

	@Override
	public SysRole save(SysRole sysRole) throws Exception {
		
		return sysRoleDao.save(sysRole);
	}

	@Override
	public void delete(SysRole sysRole) throws Exception {
		sysRoleDao.delete(sysRole);
		
	}
}
